package com.zxq.tcp.handler;


import com.zxq.tcp.cache.TcpChannelCache;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public  class TCPSplitFrameDecoder extends ByteToMessageDecoder {


    TCPDispatchHandlerGatherProxy TCPDispatchHandlerGatherProxy;
    public TCPSplitFrameDecoder() {
        TCPDispatchHandlerGatherProxy = new TCPDispatchHandlerGatherProxy();
     }


    public TCPDispatchHandlerGatherProxy getTCPDispatchHandlerGatherProxy() {
        return TCPDispatchHandlerGatherProxy;
    }

    /**
     * 分发不同的通信协议
     * @param channelHandlerContext 通道
     * @param byteBuf 缓存
     * @param list 转移的数据对象
     */
    //分发不同的通信协议
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        TCPDispatchHandlerGatherProxy.injectByteBuf(channelHandlerContext,byteBuf);
        TCPDispatchHandlerGatherProxy.decodeFrame();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info(String.format("ctx:{0} close", TcpChannelCache.getDevId(ctx)));
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        TcpChannelCache.removeChannel(ctx);
    }





}
